package com.fight.strive.sys.modules.cauth.interceptor;

import com.fight.strive.sys.modules.exception.exceptions.StriveAccessDeniedException;
import com.fight.strive.sys.modules.cauth.entity.AppClientEntity;
import com.fight.strive.sys.modules.cauth.service.AppClientService;
import com.fight.strive.sys.utils.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 安全认证拦截器
 */
@Component
public class StriveCAuthInterceptor implements HandlerInterceptor {

    @Resource
    private AppClientService appClientService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            // 跨域处理
            return true;
        }
        String appKey = request.getHeader("appKey");
        String token = request.getHeader("token");
        String timespan = request.getHeader("timespan");
        String path = request.getServletPath();
        if (StringUtils.isNoneBlank(appKey, token, timespan)) {
            // 验证token的合法性
            AppClientEntity entity =
                    appClientService.validToken(appKey, token, timespan);
            if (!path.startsWith(entity.getPath())) {
                // 如果请求的路径不对，就无权限访问。
                throw new StriveAccessDeniedException();
            }
            return true;
        } else {
            throw new StriveAccessDeniedException();
        }
    }

}
